<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/auth.php';
require_once '../includes/user.php';

// 检查权限
$auth = getAuth();
$auth->requirePermission('super_admin');

// 获取当前用户信息
$currentUser = $auth->getCurrentUser();

// 初始化数据库和用户管理器
$database = getDatabaseConnection();
$userManager = new UserManager($database);

// 处理表单提交
$message = '';
$messageType = '';

if ($_POST) {
    $action = $_POST['action'] ?? '';
    
    try {
        switch ($action) {
            case 'add_user':
                // 验证用户名是否已存在
                if ($userManager->usernameExists($_POST['username'])) {
                    throw new Exception('用户名已存在');
                }
                
                $userData = [
                    'username' => $_POST['username'],
                    'password' => $_POST['password'],
                    'role' => $_POST['role'],
                    'email' => $_POST['email'],
                    'full_name' => $_POST['full_name'],
                    'department' => $_POST['department'],
                    'position' => $_POST['position'],
                    'phone' => $_POST['phone'],
                    'status' => isset($_POST['status']) ? 1 : 0
                ];
                
                if ($userManager->addUser($userData)) {
                    $message = '用户添加成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('添加用户失败');
                }
                break;
                
            case 'edit_user':
                $userId = $_POST['user_id'];
                $userData = [
                    'username' => $_POST['username'],
                    'role' => $_POST['role'],
                    'email' => $_POST['email'],
                    'full_name' => $_POST['full_name'],
                    'department' => $_POST['department'],
                    'position' => $_POST['position'],
                    'phone' => $_POST['phone'],
                    'status' => isset($_POST['status']) ? 1 : 0
                ];
                
                // 验证用户名是否已存在（排除当前用户）
                if ($userManager->usernameExists($_POST['username'], $userId)) {
                    throw new Exception('用户名已存在');
                }
                
                if ($userManager->updateUser($userId, $userData)) {
                    $message = '用户信息更新成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('更新用户信息失败');
                }
                break;
                
            case 'delete_user':
                $userId = $_POST['user_id'];
                if ($userManager->deleteUser($userId)) {
                    $message = '用户删除成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('删除用户失败');
                }
                break;
                
            case 'reset_password':
                $userId = $_POST['user_id'];
                $newPassword = $_POST['new_password'];
                if ($userManager->updatePassword($userId, $newPassword)) {
                    $message = '密码重置成功';
                    $messageType = 'success';
                } else {
                    throw new Exception('密码重置失败');
                }
                break;
        }
    } catch (Exception $e) {
        $message = $e->getMessage();
        $messageType = 'danger';
    }
}

// 获取查询参数
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
$search = $_GET['search'] ?? '';

// 获取用户列表
$usersData = $userManager->getAllUsers($page, $limit, $search);
$users = $usersData['users'];
$total = $usersData['total'];
$totalPages = $usersData['total_pages'];

// 获取用户统计
$userStats = $userManager->getUserStats();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 考勤管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- 侧边栏 -->
    <?php include_once '../includes/sidebar.php'; ?>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand navbar-custom mb-4">
            <div class="container-fluid">
                <div class="navbar-nav me-auto">
                    <span class="navbar-text">
                        <i class="fas fa-users me-2"></i>用户管理
                    </span>
                </div>
                <div class="navbar-nav">
                    <span class="navbar-text me-3">
                        <i class="fas fa-user me-2"></i>
                        <?php echo htmlspecialchars($currentUser['full_name']); ?>
                    </span>
                    <a href="../user/profile.php" class="nav-link">
                        <i class="fas fa-cog"></i> 个人设置
                    </a>
                </div>
            </div>
        </nav>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                <i class="fas fa-<?php echo $messageType === 'success' ? 'check' : 'exclamation-triangle'; ?> me-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- 用户统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-2">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $userStats['total_users']; ?></h4>
                        <p class="mb-0">总用户数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $userStats['active_users']; ?></h4>
                        <p class="mb-0">活跃用户</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-warning text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $userStats['inactive_users']; ?></h4>
                        <p class="mb-0">禁用用户</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $userStats['super_admins']; ?></h4>
                        <p class="mb-0">管理员</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-secondary text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $userStats['normal_users']; ?></h4>
                        <p class="mb-0">普通用户</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-dark text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $userStats['guests']; ?></h4>
                        <p class="mb-0">游客</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="fas fa-users me-2"></i>用户列表
                </h5>
                <div>
                    <!-- 搜索表单 -->
                    <form method="get" class="d-inline me-2">
                        <div class="input-group input-group-sm">
                            <input type="text" name="search" class="form-control" placeholder="搜索用户..." 
                                   value="<?php echo htmlspecialchars($search); ?>">
                            <button class="btn btn-outline-secondary" type="submit">
                                <i class="fas fa-search"></i>
                            </button>
                            <?php if ($search): ?>
                                <a href="users.php" class="btn btn-outline-danger">
                                    <i class="fas fa-times"></i>
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addUserModal">
                        <i class="fas fa-user-plus me-2"></i>添加用户
                    </button>
                </div>
            </div>
            <div class="card-body">
                <?php if (empty($users)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-users fa-4x mb-3"></i>
                        <h4>暂无用户数据</h4>
                        <p>点击"添加用户"按钮创建第一个用户</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>姓名</th>
                                    <th>角色</th>
                                    <th>部门</th>
                                    <th>职位</th>
                                    <th>邮箱</th>
                                    <th>状态</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($users as $user): ?>
                                    <tr>
                                        <td><?php echo $user['id']; ?></td>
                                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                                        <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                                        <td>
                                            <span class="badge 
                                                <?php echo $user['role'] === 'super_admin' ? 'bg-danger' : 
                                                      ($user['role'] === 'user' ? 'bg-primary' : 'bg-secondary'); ?>">
                                                <?php echo $user['role'] === 'super_admin' ? '管理员' : 
                                                      ($user['role'] === 'user' ? '用户' : '游客'); ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($user['department']); ?></td>
                                        <td><?php echo htmlspecialchars($user['position']); ?></td>
                                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                                        <td>
                                            <span class="badge <?php echo $user['status'] ? 'bg-success' : 'bg-danger'; ?>">
                                                <?php echo $user['status'] ? '启用' : '禁用'; ?>
                                            </span>
                                        </td>
                                        <td><?php echo date('Y-m-d H:i', strtotime($user['created_at'])); ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button class="btn btn-outline-primary" 
                                                        data-bs-toggle="modal" 
                                                        data-bs-target="#editUserModal"
                                                        onclick="loadUserData(<?php echo $user['id']; ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-outline-warning" 
                                                        data-bs-toggle="modal" 
                                                        data-bs-target="#resetPasswordModal"
                                                        onclick="setResetPasswordUser(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>')">
                                                    <i class="fas fa-key"></i>
                                                </button>
                                                <?php if ($user['id'] != $currentUser['id']): ?>
                                                    <button class="btn btn-outline-danger" 
                                                            onclick="confirmDelete(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['username']); ?>')">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <button class="btn btn-outline-secondary" disabled>
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页 -->
                    <?php if ($totalPages > 1): ?>
                        <nav>
                            <ul class="pagination justify-content-center">
                                <?php if ($page > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?php echo $page-1; ?>&limit=<?php echo $limit; ?>&search=<?php echo urlencode($search); ?>">上一页</a>
                                    </li>
                                <?php endif; ?>
                                
                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                    <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                        <a class="page-link" href="?page=<?php echo $i; ?>&limit=<?php echo $limit; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <?php if ($page < $totalPages): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?php echo $page+1; ?>&limit=<?php echo $limit; ?>&search=<?php echo urlencode($search); ?>">下一页</a>
                                    </li>
                                <?php endif; ?>
                            </ul>
                        </nav>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- 添加用户模态框 -->
    <div class="modal fade" id="addUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post">
                    <div class="modal-header">
                        <h5 class="modal-title">添加用户</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add_user">
                        <div class="mb-3">
                            <label class="form-label">用户名 *</label>
                            <input type="text" name="username" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">密码 *</label>
                            <input type="password" name="password" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">确认密码 *</label>
                            <input type="password" name="confirm_password" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">姓名 *</label>
                            <input type="text" name="full_name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">角色 *</label>
                            <select name="role" class="form-select" required>
                                <option value="user">普通用户</option>
                                <option value="super_admin">管理员</option>
                                <option value="guest">游客</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">邮箱</label>
                            <input type="email" name="email" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">部门</label>
                            <input type="text" name="department" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">职位</label>
                            <input type="text" name="position" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">电话</label>
                            <input type="text" name="phone" class="form-control">
                        </div>
                        <div class="mb-3 form-check">
                            <input type="checkbox" name="status" class="form-check-input" checked>
                            <label class="form-check-label">启用账户</label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">添加用户</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post">
                    <div class="modal-header">
                        <h5 class="modal-title">编辑用户</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="edit_user">
                        <input type="hidden" name="user_id" id="edit_user_id">
                        <div class="mb-3">
                            <label class="form-label">用户名 *</label>
                            <input type="text" name="username" id="edit_username" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">姓名 *</label>
                            <input type="text" name="full_name" id="edit_full_name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">角色 *</label>
                            <select name="role" id="edit_role" class="form-select" required>
                                <option value="user">普通用户</option>
                                <option value="super_admin">管理员</option>
                                <option value="guest">游客</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">邮箱</label>
                            <input type="email" name="email" id="edit_email" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">部门</label>
                            <input type="text" name="department" id="edit_department" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">职位</label>
                            <input type="text" name="position" id="edit_position" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">电话</label>
                            <input type="text" name="phone" id="edit_phone" class="form-control">
                        </div>
                        <div class="mb-3 form-check">
                            <input type="checkbox" name="status" id="edit_status" class="form-check-input">
                            <label class="form-check-label">启用账户</label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">保存修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 重置密码模态框 -->
    <div class="modal fade" id="resetPasswordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post">
                    <div class="modal-header">
                        <h5 class="modal-title">重置密码</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="action" value="reset_password">
                        <input type="hidden" name="user_id" id="reset_user_id">
                        <div class="mb-3">
                            <label class="form-label">用户名</label>
                            <input type="text" id="reset_username" class="form-control" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">新密码 *</label>
                            <input type="password" name="new_password" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">确认新密码 *</label>
                            <input type="password" name="confirm_new_password" class="form-control" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-warning">重置密码</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 删除用户表单 -->
    <form id="deleteForm" method="post" style="display: none;">
        <input type="hidden" name="action" value="delete_user">
        <input type="hidden" name="user_id" id="delete_user_id">
    </form>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 加载用户数据到编辑模态框
        function loadUserData(userId) {
            fetch(`../api/get_user.php?id=${userId}`)
                .then(response => response.json())
                .then(user => {
                    document.getElementById('edit_user_id').value = user.id;
                    document.getElementById('edit_username').value = user.username;
                    document.getElementById('edit_full_name').value = user.full_name;
                    document.getElementById('edit_role').value = user.role;
                    document.getElementById('edit_email').value = user.email || '';
                    document.getElementById('edit_department').value = user.department || '';
                    document.getElementById('edit_position').value = user.position || '';
                    document.getElementById('edit_phone').value = user.phone || '';
                    document.getElementById('edit_status').checked = user.status == 1;
                })
                .catch(error => {
                    console.error('Error loading user data:', error);
                    alert('加载用户数据失败');
                });
        }

        // 设置重置密码的用户
        function setResetPasswordUser(userId, username) {
            document.getElementById('reset_user_id').value = userId;
            document.getElementById('reset_username').value = username;
        }

        // 确认删除用户
        function confirmDelete(userId, username) {
            if (confirm(`确定要删除用户 "${username}" 吗？此操作不可逆！`)) {
                document.getElementById('delete_user_id').value = userId;
                document.getElementById('deleteForm').submit();
            }
        }

        // 表单验证
        document.addEventListener('DOMContentLoaded', function() {
            // 添加用户表单密码验证
            const addForm = document.querySelector('#addUserModal form');
            addForm.addEventListener('submit', function(e) {
                const password = this.querySelector('input[name="password"]').value;
                const confirmPassword = this.querySelector('input[name="confirm_password"]').value;
                
                if (password !== confirmPassword) {
                    e.preventDefault();
                    alert('两次输入的密码不一致！');
                }
            });

            // 重置密码表单验证
            const resetForm = document.querySelector('#resetPasswordModal form');
            resetForm.addEventListener('submit', function(e) {
                const newPassword = this.querySelector('input[name="new_password"]').value;
                const confirmNewPassword = this.querySelector('input[name="confirm_new_password"]').value;
                
                if (newPassword !== confirmNewPassword) {
                    e.preventDefault();
                    alert('两次输入的新密码不一致！');
                }
            });
        });
    </script>
</body>
</html>
